<template>
  <div class='container'>
      <el-dialog
      :title="title"
      :visible="visible"
      @close="cancel"
      width="30%"
      >
      <el-form  :model="formData" :rules="rules" label-width="100px" ref="refForm" >
      <el-form-item  label="学科名称" prop="subjectName">
        <el-input v-model="formData.subjectName" placeholder="请输入学科名称" />
      </el-form-item>
      <el-form-item  label="是否显示">
      <el-switch
        v-model="value"
        active-color="#13ce66"
        inactive-color="#ff4949">
      </el-switch>
       </el-form-item>
       </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>

      </el-dialog>
  </div>
</template>

<script>
import { add, update, detail } from '../../api/hmmm/subjects'
export default {
  name: 'subjectsadd',
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    detail: {
      type: Object,
      required: true
    }

  },
  data () {
    return {
      value: true,
      formData: {
        subjectName: ''
      },
      // 表单的校验规则
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: ['change', 'blur'] }
        ]
      },
      title: '新增学科',
      isFrontDisplay: 0

    }
  },
  methods: {
    changeValue () {
      if (this.value === true) {
        this.isFrontDisplay = 1
      } else {
        this.isFrontDisplay = 0
      }
    },
    handleSubmit () {
      // 新增提交
      // 1. 预校验
      this.$refs.refForm.validate(async boo => {
        if (!boo) return
        if (this.detail.id) {
          // 更新部门的请求
          console.log(this.detail)
          await update({
            id: this.detail.id,
            subjectName: this.formData.subjectName,
            isFrontDisplay: this.isFrontDisplay
          })
          this.detail.id = null
        } else {
        // 2. 新增部门请求
          console.log(this.detail)
          await add({
            subjectName: this.formData.subjectName,
            isFrontDisplay: this.isFrontDisplay

          })
        }
        // 3. 通知父组件关闭对话框并重新获取部门列表
        this.$emit('closeDialog')
        this.formData = { subjectName: '' }
        this.value = true
      })
    },
    // 取消按钮和x号按钮
    cancel () {
      this.$emit('update:visible', false)
      // 重置表单
      this.$refs.refForm.resetFields()
      // 将form初始化所有字段为空值
      this.formData = { subjectName: '' }
      this.value = true
    },
    async getInfo (id) {
      // console.log('获取部门信息')
      // 根据id查询部门详情
      const { data } = await detail({ id: id })
      console.log(data)
      this.formData.subjectName = data.subjectName
    }
  }
}
</script>

<style scoped lang='less'></style>
